package com.example.yingjiguanli_demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yingjiguanli_demo.pojo.Announcements;
import com.example.yingjiguanli_demo.mapper.AnnouncementsMapper;
import com.example.yingjiguanli_demo.pojo.Result;
import com.example.yingjiguanli_demo.service.IAnnouncementsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.formula.functions.T;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.ws.Action;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author scj
 * @since 2024-11-13
 */
@Service
public class AnnouncementsServiceImpl extends ServiceImpl<AnnouncementsMapper, Announcements> implements IAnnouncementsService {
    @Autowired
    private AnnouncementsMapper announcementsMapper;

    /***
     * 添加公告
     * @param announcements 公告对象
     * @return Result<T>
     */
    @Override
    public Result<T> add(Announcements announcements) {
        // 防止XSS攻击：清理用户输入的评论内容
        String Content = announcements.getContent();
        if (Content != null) {
            // 使用Jsoup清理内容，移除所有HTML标签，保留纯文本
            Content = Jsoup.clean(Content, Safelist.none());
            // 或者，如果需要保留一些基本标签，可以使用 Safelist.basic()
            announcements.setContent(Content);
        }
        boolean isSaved = this.save(announcements);
        if (isSaved) {
            return Result.success();
        } else {
            return Result.failed();
        }
    }

    /***
     * 获取最近的公告
     * @return Result<Announcements>
     */
    @Override
    public Result<Announcements> get() {
        // 使用QueryWrapper构建查询条件
        QueryWrapper<Announcements> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .le("start_date", LocalDateTime.now())  // 筛选已经开始的公告
                .orderByDesc("start_date")  // 按开始时间倒序排列
                .last("LIMIT 1");  // 取最近的一条记录

        // 执行查询
        Announcements nearestAnnouncement = announcementsMapper.selectOne(queryWrapper);

        // 检查查询结果并返回
        if (nearestAnnouncement != null) {
            return Result.success(nearestAnnouncement);
        } else {
            return Result.failed("没有找到公告！");
        }
    }
}
